#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: KevinQi
@file: jwt_utils.py
@time: 2023/12/27 1:33
@desc:
"""

import jwt
import datetime
from jwt import exceptions

from backend.workjob.utils.response_utils import JsonUtils

JWT_SALT = '1qazxdr5'


def create_token(payload, timeout=12):
    """
    创建token
    :param payload:  例如：{'user_id':1,'username':'xxx@xxx.xx'}用户信息
    :param timeout: token的过期时间，默认20分钟
    :return:
    """
    headers = {
        'typ': 'jwt',
        'alg': 'HS256'
    }
    payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout)
    result = jwt.encode(payload=payload, key=JWT_SALT, algorithm="HS256", headers=headers).decode('utf-8')
    return result


def parse_payload(token):
    """
    对token进行校验并获取payload
    :param token:
    :return:
    """
    try:
        verified_payload = jwt.decode(token, JWT_SALT, True)
        print(verified_payload)
        return JsonUtils.success('认证通过')
    except exceptions.ExpiredSignatureError:
        return JsonUtils.noAuth('token已失效')
    except jwt.DecodeError:
        return JsonUtils.noAuth('token认证失败')
    except jwt.InvalidTokenError:
        return JsonUtils.noAuth('非法的token')

